package chatManagers;

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ChatList extends HttpServlet {
    
    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        //DBMSManager dbm= new DBMSManager(request.getParameter("db"));
        DBMSManager dbm = new DBMSManager();
        String chatType = "" + request.getParameter("chatType");
        String platform = "" + request.getParameter("platform");
        
        // If no chat type was specified on the JSP page, default to an expert chat.
        if(chatType.equals("")) {
            chatType = "expert";
        }
        
        HttpSession session=request.getSession(true);
        UserBean ub = new UserBean();
        session.setAttribute("ub",ub);
        
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
        int uid;
        int availableChats = 0;
        ResultSet rs = null;
        
        if(request.getRemoteUser()!=null) {
            String uName = request.getRemoteUser();
            String[] uGroups = dbm.getGroups(uName);
            
            // Check if the user is allowed to chat;
            uid = dbm.checkLogin(uName);
            
            if(uid > 0) {
                // Set the user and chat IDs in the UserBean
                ub.setuserid(uid);
                ub.setchatid(0); // initially, no chat
                
                rs = dbm.getAllOpenChats(chatType);
                try {
                    while(rs.next()) {
                        int id = rs.getInt("id");
                        String usersString = rs.getString("users");
                        if(dbm.isChatActive(id) && this.isAuthorizedGroup(usersString, uGroups)) {
                            String nameString = rs.getString("name");
                            String descString = rs.getString("description");
                            out.print("<p><strong>");
                            out.print("<a target=\"_blank\" href=\"chat");
                            if(platform.equals("mobile")){
                                out.print("_m");
                            }
                            out.print(".jsp?chatid=" + id);
                            out.println("&chatName=" + nameString + "\">");
                            out.println(nameString + "</a></strong><br>" + descString);
                            out.println("</p>");
                            availableChats++;
                        }
                    }
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                } finally {
                    dbm.closeConnection();
                }
            }
            if(availableChats <= 0) {
                out.println("<p><span style=\"color:ff0000\">Sorry</span>, but " +
                        "there are no chats available for you to join right now.</p>");
            }
        }
    }
    
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
    /** Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
    /** Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }
// </editor-fold>

    private boolean isAuthorizedGroup(String uString, String[] uGroups) {
        boolean authorized = false;
        for(int i=0; i<uGroups.length; i++) {
            if(uString.contains(uGroups[i]) || uString.equals("*")) {
                authorized = true;
            }
        }
        return authorized;
    }
}
